package com.jasonm.rssminer.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.MappingSqlQuery;

import com.jasonm.rssminer.dto.SearchDTO;

public class SearchDAO {

	static String query = "select id, query from rssminer.search join rssminer.user_search on user_search.user_id = ? and user_search.search_id = search.id";

	private class SearchDAOInner extends MappingSqlQuery<SearchDTO> {

		public SearchDAOInner(DataSource ds) {
			super(ds, query);
			super.declareParameter(new SqlParameter("user_id", Types.INTEGER));
			compile();
		}

		@Override
		protected SearchDTO mapRow(ResultSet rs, int rowNumber)
				throws SQLException {
			SearchDTO searchDTO = new SearchDTO();
			searchDTO.setId((Integer) rs.getObject("id"));
			searchDTO.setQuery((String) rs.getObject("query"));
			return searchDTO;
		}

	}

	private SearchDAOInner daoInner;

	public SearchDAO(DataSource ds) {
		if (daoInner == null) {
			daoInner = new SearchDAOInner(ds);
		}
	}

	public List<SearchDTO> getSearches(Integer userId) {
		List<SearchDTO> searches = daoInner.execute(userId);
		return searches;
	}

}
